<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>言论详情 - 信院数字人后台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        :root{--color-primary:#003366;--color-danger:#d7000f;--color-border:#d0d0d0;--color-row-hover:#f5f7fa;}
        body{font-family:"Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;background:#f3f4f6;font-size:14px;}
        .sidebar{width:240px;background:#001529;color:#c7d0d9;display:flex;flex-direction:column;}
        .sidebar .logo{height:64px;display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:600;background:#002140;color:#fff;padding:0 16px;}
        .sidebar .logo img{width:40px;height:40px;border-radius:50%;margin-right:12px;object-fit:contain;background:#fff;padding:2px;}
        .sidebar .menu a{display:block;padding:12px 24px;font-size:14px;transition:background .2s;}
        .sidebar .menu a:hover,.sidebar .menu a.active{background:#1890ff;color:#fff;}
        .topbar{height:64px;background:#fff;border-bottom:1px solid var(--color-border);padding:0 24px;display:flex;align-items:center;justify-content:space-between;}
        .btn{display:inline-flex;align-items:center;justify-content:center;padding:6px 16px;font-size:14px;border:1px solid var(--color-border);background:#fff;cursor:pointer;transition:all .2s;border-radius:4px;}
        .btn-primary{background:var(--color-primary);color:#fff;border-color:var(--color-primary);}
        .btn-primary:hover{background:#004080;}
        .btn-danger{color:var(--color-danger);border-color:var(--color-danger);}
        .btn-danger:hover{background:var(--color-danger);color:#fff;}
        .data-table{width:100%;border-collapse:collapse;border-spacing:0;empty-cells:show;border:1px solid var(--color-border);}
        .data-table thead{background-color:#f5f7fa;color:#333;}
        .data-table th,.data-table td{padding:12px 16px;border-bottom:1px solid var(--color-border);border-right:1px solid var(--color-border);text-align:left;word-break:break-all;line-height:1.4;vertical-align:middle;}
        .data-table th:last-child,.data-table td:last-child{border-right:none;}
        .data-table tr:hover{background-color:var(--color-row-hover);}
        .data-table th.id-col{width:60px;}.data-table th.status-col{width:100px;}.data-table th.time-col{width:160px;}.data-table th.action-col{width:100px;text-align:center;}
        .data-table td.action-col{text-align:center;}
        .action-btn{display:inline-block;width:28px;height:28px;line-height:28px;text-align:center;border-radius:4px;margin:0 4px;cursor:pointer;transition:all .2s;color:#666;border:1px solid transparent;}
        .action-btn:hover{background-color:#f0f0f0;border-color:#ddd;}
        .action-btn.edit{color:#1890ff;}.action-btn.edit:hover{background-color:#e6f7ff;border-color:#bae7ff;}
        .action-btn.delete{color:#ff4d4f;}.action-btn.delete:hover{background-color:#fff2f0;border-color:#ffccc7;}
        .status-badge{display:inline-block;padding:2px 8px;border-radius:10px;font-size:12px;}
        .status-normal{background:#e6f7ff;color:#1890ff;}
        .status-banned{background:#fff2f0;color:#ff4d4f;}
        .form-input{width:100%;padding:7px 11px;border:1px solid var(--color-border);font-size:14px;transition:border-color .2s;border-radius:4px;}
        .form-input:focus{border-color:var(--color-primary);outline:none;box-shadow:0 0 0 2px rgba(0,51,102,.2);}
        .pagination{font-size:14px;display:flex;align-items:center;gap:8px;}
        .pagination .btn:disabled{opacity:.6;cursor:not-allowed;}
        main {
            padding-bottom: 60px !important;
        }
        #page {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            background: white;
            z-index: 10;
            border-top: 1px solid var(--color-border);
            box-shadow: 0 -2px 8px rgba(0,0,0,0.05);
        }
    </style>
</head>
<body class="flex h-screen overflow-hidden">
<aside class="sidebar">
    <div class="logo"><img src="/logo/logo.jpg" alt="logo" onerror="this.src='https://picsum.photos/40/40?random=logo';this.style.background='#fff';">信院数字人后台</div>
    <nav class="menu flex-1 pt-4">
        <a href="/admin/usersManage.html"><i class="fa fa-user-o mr-2"></i>用户管理</a>
        <a href="/admin/postsManage.html" class="active"><i class="fa fa-comments-o mr-2"></i>言论详情</a>
        <a href="/admin/imagesManage.html"><i class="fa fa-image mr-2"></i>图片管理</a>
        <a href="/admin/filesManage.html"><i class="fa fa-file-o mr-2"></i>文件管理</a>
    </nav>
</aside>

<section class="flex-1 flex flex-col">
    <header class="topbar">
        <div class="text-base font-medium">言论详情</div>
        <div class="flex items-center gap-4"><span class="text-sm">管理员</span><img src="/logo/guanliyuan.png" class="w-8 h-8 rounded-full"></div>
    </header>

    <main class="flex-1 overflow-y-auto p-6">
        <div class="bg-white border border-gray-200 rounded px-4 py-3 mb-4">
            <div class="flex flex-col md:flex-row gap-4">
                <div class="flex-1">
                    <input id="postKeyword" type="text" placeholder="请输入言论内容" class="form-input w-full">
                </div>
                <div class="flex items-center gap-2">
                    <input id="startDate" type="date" class="form-input w-40">
                    <span>至</span>
                    <input id="endDate" type="date" class="form-input w-40">
                </div>
                <div class="flex items-center gap-2">
                    <select id="postStatusFilter" class="form-input w-32">
                        <option value="">全部状态</option>
                        <option value="0">正常</option>
                        <option value="1">禁用</option>
                    </select>
                    <select id="likeOrder" class="form-input w-32">
                        <option value="desc">点赞数降序</option>
                        <option value="asc">点赞数升序</option>
                    </select>
                </div>
                <div class="flex items-center gap-2">
                    <button id="postSearchBtn" class="btn btn-primary">查询</button>
                    <button id="postResetBtn" class="btn">重置</button>
                </div>
            </div>
        </div>

        <div class="bg-white rounded overflow-x-auto shadow-sm">
            <table class="data-table min-w-[800px]">
                <thead>
                <tr>
                    <th class="id-col">ID</th>
                    <th>学号/教职工号</th>
                    <th>言论内容</th>
                    <th>点赞数</th>
                    <th>评论数</th>
                    <th class="status-col">状态</th>
                    <th class="time-col">发表时间</th>
                    <th class="action-col">操作</th>
                </tr>
                </thead>
                <tbody id="postsList"></tbody>
            </table>
        </div>

        <div id="page" class="mt-4 px-4 py-2 flex items-center justify-between text-sm text-gray-600">
            <div>共 <span id="postsTotal">0</span> 条</div>
            <div class="pagination">
                <button id="postsPrev" class="btn">上一页</button>
                <span>第 <span id="postsCurr">1</span> 页 / 共 <span id="postsPages">1</span> 页</span>
                <button id="postsNext" class="btn">下一页</button>
            </div>
        </div>
    </main>
</section>

<script>
    // DOM 操作辅助函数
    function $(selector) { return document.querySelector(selector); }
    function $$(selector) { return document.querySelectorAll(selector); }

    // 发送 HTTP 请求的通用函数
    async function request(url, options = {}) {
        try {
            const defaultHeaders = {
                'Content-Type': 'application/json'
            };
            const mergedHeaders = { ...defaultHeaders, ...options.headers };
            const mergedOptions = { ...options, headers: mergedHeaders, credentials: 'include' };

            if (mergedOptions.body && typeof mergedOptions.body === 'object') {
                mergedOptions.body = JSON.stringify(mergedOptions.body);
            }

            const res = await fetch(url, mergedOptions);
            if (!res.ok) {
                throw new Error(`请求失败: ${res.status} ${res.statusText}`);
            }

            try {
                return await res.json();
            } catch (e) {
                return res.text();
            }
        } catch (e) {
            console.error('HTTP 请求错误:', e);
            throw e;
        }
    }

    // 言论详情相关变量
    let postsCurrPage = 1, postsPageSize = 6, postsTotalPages = 1;

    // 言论状态处理函数
    function getPostStatusText(status) {
        const statusMap = { 0: '正常', 1: '禁用' };
        return statusMap[status] || '未知';
    }

    function getPostStatusClass(status) {
        const classMap = { 0: 'status-normal', 1: 'status-banned' };
        return classMap[status] || '';
    }

    // 加载言论列表
    async function loadPostsTable() {
        const keyword = $('#postKeyword').value.trim();
        const startDate = $('#startDate').value;
        const endDate = $('#endDate').value;
        const status = $('#postStatusFilter').value;
        const likeOrder = $('#likeOrder').value;

        const params = new URLSearchParams({
            pageNum: postsCurrPage,
            pageSize: postsPageSize,
            keyword,
            startDate,
            endDate,
            status,
            likeOrder
        });

        try {
            const res = await request('/admin/api/posts?' + params);
            const list = res.records || [], total = res.total || 0;
            postsTotalPages = Math.max(1, Math.ceil(total / postsPageSize));
            let html = '';
            list.forEach(r => {
                html += `<tr>
                    <td class="id-col">${r.id}</td>
                    <td>${r.stuOrTeaId || '未知用户'}</td>
                    <td class="max-w-md">${r.content}</td>
                    <td>${r.likeCount || 0}</td>
                    <td>${r.commentCount || 0}</td>
                    <td class="status-col"><span class="status-badge ${getPostStatusClass(r.status)}">${getPostStatusText(r.status)}</span></td>
                    <td class="time-col">${r.createTime || '-'}</td>
                    <td class="action-col">
                        <span class="action-btn ${r.status === 0 ? 'delete' : 'edit'}" title="${r.status === 0 ? '禁用' : '启用'}" onclick="togglePostStatus(${r.id}, ${r.status === 0 ? 1 : 0})"><i class="fa fa-${r.status === 0 ? 'ban' : 'check'}"></i></span>
                    </td>
                </tr>`;
            });
            $('#postsList').innerHTML = html || '<tr><td colspan="8" class="text-center text-gray-400 py-8">暂无数据</td></tr>';
            $('#postsTotal').textContent = total;
            $('#postsCurr').textContent = postsCurrPage;
            $('#postsPages').textContent = postsTotalPages;
            $('#postsPrev').disabled = postsCurrPage === 1;
            $('#postsNext').disabled = postsCurrPage === postsTotalPages;
        } catch (e) {
            console.error('加载言论列表失败:', e);
            alert('加载言论列表失败：' + e.message);
        }
    }

    // 言论分页按钮事件
    $('#postsPrev').onclick = () => {
        if (postsCurrPage > 1) {
            postsCurrPage--;
            loadPostsTable();
        }
    };

    $('#postsNext').onclick = () => {
        if (postsCurrPage < postsTotalPages) {
            postsCurrPage++;
            loadPostsTable();
        } else {
            alert('已经是最后一页啦！');
        }
    };

    // 言论查询和重置
    $('#postSearchBtn').onclick = () => {
        postsCurrPage = 1;
        loadPostsTable();
    };

    $('#postResetBtn').onclick = () => {
        $('#postKeyword').value = '';
        $('#startDate').value = '';
        $('#endDate').value = '';
        $('#postStatusFilter').value = '';
        $('#likeOrder').value = 'desc';
        postsCurrPage = 1;
        loadPostsTable();
    };

    // 切换言论状态（禁用/启用）
    async function togglePostStatus(id, newStatus) {
        try {
            // 构建符合后端接口要求的请求体
            const requestBody = { status: newStatus };
            console.log('发送状态更新请求:', requestBody);

            // 发送状态更新请求（request函数内部会处理序列化）
            await request(`/admin/api/posts/${id}/status`, {
                method: 'PUT',
                body: requestBody
            });

            // 立即重新加载言论列表，确保状态变更立即显示
            loadPostsTable();

            // 操作成功提示
            alert('操作成功，列表已更新');
        } catch (e) {
            console.error('切换言论状态失败:', e);
            // 即使失败也尝试刷新列表，确保数据准确性
            loadPostsTable();
            alert('操作失败：' + e.message);
        }
    }

    window.onload = () => { loadPostsTable(); };
</script>
</body>
</html>
